package cs.rsa.ts14.manual;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import cs.rsa.ts14.framework.LineSequenceState;
import cs.rsa.ts14.framework.LineType;
import cs.rsa.ts14.framework.LineTypeClassifierStrategy;
import cs.rsa.ts14.framework.ReportBuilder;
import cs.rsa.ts14.standard.StandardTimesagLineProcessor;

public class Timesag2 {
	 
	
	private ReportBuilder builder;
	private LineSequenceState sequenceState;
	private LineTypeClassifierStrategy classifier;
	private StandardTimesagLineProcessor tlp;

	public Timesag2(ReportBuilder builder, LineTypeClassifierStrategy classifier, LineSequenceState initState) {
		this.builder = builder;
		this.sequenceState = initState;
	    this.classifier = classifier;
	    this.tlp = 
	        new StandardTimesagLineProcessor( 
	            this.classifier, this.builder, this.sequenceState );		
	}
	  
	public void handleFile(String filename) {

		LineIterator it = null;
		try {
		
			File f = new File(filename);
			if (f.exists() == false) {
				System.out.println("File does not exist");
				return;
			}
			it = FileUtils.lineIterator(f, "UTF-8");
	    // Create an iterator for the lines in the file
			tlp.beginProcess();
			while (it.hasNext()) {
				// process each line
				String line = it.nextLine();
				LineType linetype = tlp.process(line);
				if (linetype == LineType.INVALID_LINE) {
					System.out.println("Error in file: " + tlp.lastError());
					System.exit(-1);
				}
			}
		} catch (Exception e) {
			System.out.println("Exception while parsing: " + e.getMessage());
			e.printStackTrace();

		} finally {
			if (it != null) {
				LineIterator.closeQuietly(it);
			}
		}
		tlp.endProcess();
		// Ask the builder for the final report and print it.
		System.out.println();
		System.out.println("BUILDER RESULT: ");
		System.out.println();
		System.out.println(builder.getResult());
	  
		
	}
	
	public String getReport() {
		return builder.getResult();
	}
	
	private String getAbsolutePath() {
		return new File("").getAbsolutePath();
	}
}
	        

